Build a GraphQL API is completed
error-check
Tutorial

Upload GraphQL API to GitHub

5 steps

In the previous tutorial, we successfully built a GraphQL API that seamlessly integrates multiple Etherscan API endpoints. This provided users with a single, unified GraphQL API through which they could launch their queries for key Ethereum network metrics!

In this tutorial, we will leverage the features of Cody to enhance the overall readability of our code! This includes essential features such as code refactoring, in-line code comments and how to use Cody to generate a README.md file with ease!

Let's Begin! 🤖

Helpful prior knowledge

  • There are no pre-requisites for this tutorial

Learning Outcomes

By the end of this tutorial, you will be able to:

  • Use Cody for Code Refactoring
  • Generate In-line Code Comments
  • Enhance your README.md file
  • Upload GraphQL API Repository to GitHub

Tutorial Steps

Total steps: 5

  • Step 1: Importance of Code Readability

    In the previous tutorial, we have successfully built a GraphQL API endpoint that wraps multiple Etherscan API endpoints allowing users to initiate a single API query which returns the following response:

    • Ether Balance for Vitalik's Address
    • Total Supply of Ether 
    • Latest Price of Ethereum
    • Estimated Block Confirmation Time

    We have also tested out the functionality of the GraphQL API, and it works as expected returning all the necessary information under one single query! 

    With our functionality seamlessly integrated and tested, it's time to embark on our next journey. In this tutorial, our objective will shift towards enhancing code quality and readability with the assistance of Cody!

    Code Readability

    As developers, while we often emphasize the functionality of our code, code readability is equally as important!

    A simple analogy would be like a well-written book where it narrates a clear story without leaving the readers confused or puzzled!

    Why is Code Readability Important?

    • Facilitates Collaboration: Clear and consistent code fosters seamless collaboration where members can effortlessly build upon the work of others without requiring extensive explanations
    • Speeds Up Onboarding: Instead of grappling with the intricacies of complex code functions, readable code greatly accelerates the onboarding process leading to faster and more productive contributions
    • Improved Maintainability: When developers prioritize code readability, it’s easier to update and maintain code hence preserving the utility of the codebase

    In essence, balancing code functionality with readability fosters a comprehensive approach to software development, ensuring that our code remains a valuable asset for the long haul.

    Enhancing our GraphQL API with Cody

    To enhance our GraphQL API's readability, we won't pore over each line manually. Instead, we'll employ Cody.

    By leveraging on the functionalities of Cody, code refactoring, generating code comments and creating a comprehensive README.md for our repository is a breeze!

    Let's dive in and elevate the clarity of our codebase in the upcoming steps!

  • Step 2: Refactoring Code with Cody

    To begin, let’s start with code refactoring!

    Overview of Code Refactoring

    Code refactoring is the process of restructuring and polishing existing code snippets without altering its code functionality.

    Its primary aim is to make the code more efficient, readable, and maintainable. Refactoring plays a crucial role in software development as it helps in improving the design of existing code, making it easier to comprehend, reducing its complexity, and increasing its overall maintainability.

    By continuously refining code, developers can detect and rectify hidden bugs, improve code efficiency, and streamline the integration of new features. In essence, code refactoring ensures the code remains clean, reduces technical debt, and enhances its value and usability.

    With a better understanding of code refactoring, let’s dive into how we can leverage Cody to refactor our existing code snippet!

    To begin, head over to your index.js file on VSCode!

    Next, proceed to highlight the resolver function and enter `⌥ + C` (For Mac users) or `Alt + C` (For Windows users) and you should observe the following as shown below!

    Proceed to enter the following prompt - “Refactor this resolver” and make sure to select the “/ask” option before you hit “Enter”.

    You should observe the following output from Cody as shown below!

    Note: It’s expected for the Cody response to differ from what is shown below!

    Code Refactoring Recommendations

    • To enhance the overall readability, ensure that every resolver function indicates its purpose and functionality, opting for more descriptive function names
    • Maintain a uniform naming convention and structure for all resolver functions

    Now, with these recommendations as suggested by Cody, let's dive back into our code and refine our resolver functions. 

    ⚠️ Note: You are to copy the following code snippets as mentioned below and not the resolver functions as suggested by Cody!

    Proceed to replace the existing resolver function with the following code snippet.

    const resolvers = {
      Query: {
        etherBalanceByAddress: (root, _args, { dataSources }) =>
          dataSources.ethDataSource.etherBalanceByAddress(),
    
        totalSupplyOfEther: (root, _args, { dataSources }) =>
          dataSources.ethDataSource.totalSupplyOfEther(),
    
        latestEthereumPrice: (root, _args, { dataSources }) =>
          dataSources.ethDataSource.getLatestEthereumPrice(),
    
        blockConfirmationTime: (root, _args, { dataSources }) =>
          dataSources.ethDataSource.getBlockConfirmationTime(),
      },
    };
    JavaScript

    Updating the GraphQL Schema

    As we have made some changes to our resolver functions, we will now need to make some changes to update to the GraphQL for the refactor changes!

    Proceed to copy the following code snippet to replace the Query type under the schema.graphql file as shown below!

    Test GraphQL API

    Once you have made the changes, proceed to run the following command on your terminal to boot up the Apollo Server.

    node index.js

    Next, navigate to the Apollo Studio and proceed to enter the following code snippet and click “Run” to test out our GraphQL API.

    query {
      etherBalanceByAddress {
        message
        result
      }
      totalSupplyOfEther {
        message
        result
      }
      latestEthereumPrice {
        message
        result {
          ethbtc
          ethusd
          ethusd_timestamp
        }
      }
      blockConfirmationTime {
        message
        result
      }
    }
    GraphQL

    You should observe the query result is successful with a status message of 200 as shown below.

    How easy was that!

    With Cody's assistance, what once might've been a tedious task transforms into a seamless developer experience, making it a pleasure for any developer, whether they're revisiting your code or encountering it for the first time.

    In our subsequent phase, we'll leverage Cody's prowess to craft meaningful code comments, ensuring every function and module narrates its purpose and logic. Additionally, we'll refine our existing README.md file, ensuring it serves as a clear, comprehensive guide for any visitor to your GitHub repository.

  • Step 3: Generate Code and Refine README.md

    In this step, we will be using Cody to elevate our GitHub repository in 2 significant areas:

    • Code Comments for Better Readability
    • Revamp README.md to improve overall developer experience

    Automate Code Comments with Cody

    Instead of manually adding inline code comments to each of our functions and schema, let’s use Cody to automatically generate code comments for us!

    To begin, head over to index.js file and open the Cody Extension on your VSCode!

    Next, enter the following prompt “Insert Code Comments”.

    Shortly, you should observe the following response where code comments are automatically populated for you as shown below!

    ⚠️ Note: It’s expected for the Cody response to differ from what is shown below and this is to be expected! As long as your index.js file shows the code comments, you are good to proceed! This will apply for the upcoming files as well

    Proceed to override your existing index.js file to the code snippet with comments as suggested by Cody!

    Next, head over to the datasource/ethDatasource.js file and proceed to do the following as above to generate the code comments!

    You should observe the following as shown below.

    Proceed to override your existing datasource/ethDatasource.js file with the code suggestions with comments!

    How easy was that? Within seconds, our code snippets are now populated with easy-to-follow code comments enhancing the overall readability of our code repository!

    Refine README.md with Cody

    Finally, we will be using Cody to enhance our existing README.md file which only has the following sections - Recap of Bounty & Getting Started.

    Now, let’s utilize Cody to greatly optimize our existing README.md! Proceed to head over to Cody Chat and enter the following prompt as shown below.

    You should observe the following suggestion by Cody as shown below.

    Proceed to override the existing README.md file with the following README.md code below!

    # GraphQL With Etherscan APIs
    
    ## Getting Started
    
    To get started using the GraphQL Etherscan API, follow these steps:
    
    1. Clone this repository
    2. Run `npm install` to install dependencies
    3. Create an Etherscan API key (explained below)
    4. Start the Apollo server (explained below)
    5. Make GraphQL queries against the server (example below)
    
    ## Benefits of using GraphQL API
    
    Wrapping the Etherscan REST APIs in a GraphQL API provides the following benefits:
    
    - Query multiple related resources in a single API call
    - Strong typing system
    - Intuitive query language
    - Built-in documentation
    
    ## Create an Etherscan API Key
    
    To use the Etherscan APIs, you'll need an API key. Follow these steps:
    
    1. Sign up for an Etherscan account at https://etherscan.io/register
    2. Go to https://etherscan.io/myapikey to generate an API key
    3. Add the API key to a `.env` file as `ETHERSCAN_API=your_api_key`
    
    ## Overview of GraphQL Etherscan API endpoints
    
    The GraphQL API wraps the following Etherscan REST endpoints:
    
    - `etherBalanceByAddress` - Get ETH balance for an address
    - `totalSupplyOfEther` - Get total ETH supply
    - `latestEthereumPrice` - Get latest ETH price
    - `blockConfirmationTime` - Get estimated block confirmation time
    
    See the `schema.graphql` file for details.
    Markdown

    Optimizing README.md

    Next, we will be optimizing our README.md file by adding the following instructions to get users to run an Apollo Server and initiate a sample query!

    To begin, proceed to copy the following code snippet and add it to the existing README.md file!

    ## How to run Apollo Server
    
    Starting the Apollo GraphQL Server:
    
    1. Open your terminal on VSCode
    2. Run the following command to start the server: `node index.js`
    3. Upon successful startup, you should see this message: 🚀 Server ready at http://localhost:9000/
    4. Access the Apollo Server by navigating to http://localhost:9000 on your browser
    
    ## Sample GraphQL Query
    
    Below is a sample GraphQL query to fetch the necessary data from Etherscan
    Markdown

    Next, proceed to add the following GraphQL Query to the Sample GraphQL Query Section on your current README.md to fetch the necessary data from Etherscan using your GraphQL API!

    ```graphql
    query {
      etherBalanceByAddress {
        message
        result
      }
      totalSupplyOfEther {
        message
        result
      }
      latestEthereumPrice {
        message
        result {
          ethbtc
          ethusd
          ethusd_timestamp
        }
      }
      blockConfirmationTime {
        message
        result
      }
    }
    ```
    GraphQL

    Thanks to Cody, not only is our code now richly commented, but our README.md is also streamlined and developer-friendly!

    In the next step, we will walk you through how to upload your code to GitHub!

  • Step 4: Upload GraphQL API to GitHub Repository

    In this step, we will be uploading our revised GraphQL API code to GitHub!

    To begin, head over to GitHub and login to your account! Proceed to sign up for a new GitHub account if you do not already have one!

    Next, proceed to create a new GitHub repository and name the repository “my_etherscan_graphql” and click on “Create repository”.

    Upon creating a new repository, you should observe the following as shown below.

    Next, click on “uploading an existing file” as shown below.

    Proceed to upload all your working files excluding node_modules. Here’s how it should look like.

    Next, click on “Commit changes”.

    Your README.md now serves as a welcoming guide, while the polished code comments make your codebase transparent and easy to understand. This exceptional transformation is a testament to Cody's capabilities!

    With Cody by your side, you've transformed not just code, but also the very experience of any developer who interacts with your project!

    With that, you are done with this tutorial, and you also have a copy of your code saved in your repository. 

  • Step 5: [For Earn Quest Submission]

    Note: This step is only applicable to the Earn app, and was part of the Cody AI campaign that ran in November 2023.

    You have reached the end! Now to make sure you successfully complete this quest! There is 1 deliverable that is required for this quest, a link to your GitHub repository!

    GitHub Repository Link

    Your GitHub Repository should contain:

    • The following sections - Getting Started, Benefits of using GraphQL API, Create an Etherscan API key, Overview of GraphQL Etherscan API endpoints, How to run Apollo Server and Sample GraphQL Query
    • A sample GraphQL query to interact with the Apollo Server

    By submitting the quest, please note that our StackUp Policy prohibits the use of multiple accounts by a single user and the submission of copied work.

Have you completed this tutorial? Click below to mark as complete

Help Center Need help?

Find articles to support you through your journey or chat with our support team.

Help Center